package com.regex.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.regex.web.baidu.ai.image.General;
import com.regex.web.utils.AjaxUtil;

@Controller
@RequestMapping("wx/image")
public class ImageUtilsController {
	
	@RequestMapping("analysis")
	public String getImageAnalysisText() {
		return "wx/input";
	}
	
	@RequestMapping("index")
	public String index(String url, Model model) {
		model.addAttribute("url", url);
		return "wx/index";
	}
	
	@RequestMapping("demo")
	public String demo(String url, Model model) {
		model.addAttribute("url", url);
		return "wx/demo";
	}
	
	@RequestMapping("recognition")
	public void recognition(String base64Img, String fileName, HttpServletResponse response,
			HttpServletRequest request) {
		
		String TrueDirectory = "ImgFiles"+File.separator+"backgroundImg";
        String inventedDirectory = "ImgFiles/"+"backgroundImg";
        String directory = TrueDirectory+"-"+inventedDirectory;
        Map<String, String> map = uploadImgBase64(request,base64Img, directory, fileName);
		
		
        System.out.println("url!=====" + JSON.toJSONString(map));
        String url = map.get("path");
        System.out.println("url!=====" + url);
        String datas =  General.getLocalPicText(url);
		AjaxUtil.ajaxJsonSucMessage(response, datas);		
	}
	
	
	public static Map<String, String> uploadImgBase64(HttpServletRequest request,String imgBase64,String Directory,String oldFileName){  
        Map<String, String> uploadImageMap  =  new HashMap<String, String>();
        String oldFileName2 = oldFileName.substring(0,oldFileName.lastIndexOf("."));
        String lastFileName = oldFileName.substring(oldFileName.lastIndexOf("."),oldFileName.length());
        String fileName =  oldFileName2+System.currentTimeMillis()+lastFileName;// 重命名上传后的文件名
        uploadImageMap.put("oldFileName", oldFileName);
        //上传本地tomcat路径
        String path = request.getSession().getServletContext().getRealPath("/") + Directory.split("-")[0] + File.separator+ fileName;
        String filePath = request.getSession().getServletContext().getRealPath("/") + Directory.split("-")[0];
        //上传服务器路径
        String phoUrl = "/" + Directory.split("-")[1]+"/" + fileName;

        String header ="data:image";  
        String[] imageArr=imgBase64.split(",");  
        if(imageArr[0].contains(header)){//是img的  
            // 去掉头部  
            imgBase64=imageArr[1];  
            //image = image.substring(header.length());  
            // 写入磁盘  
            Decoder decoder = Base64.getDecoder();   
            try{  
                 byte[] decodedBytes = decoder.decode(imgBase64);        //将字符串格式的image转为二进制流（biye[])的decodedBytes  
                 File targetFile = new File(filePath);  
                 if(!targetFile.exists()){    
                     targetFile.mkdirs();    
                 }    

                 FileOutputStream out = new FileOutputStream(path);        //新建一个文件输出器，并为它指定输出位置imgFilePath  
                 out.write(decodedBytes); //利用文件输出器将二进制格式decodedBytes输出  
                 out.flush(); 
                 out.close();                        //关闭文件输出器  
                 uploadImageMap.put("success", "上传文件成功！");
                 uploadImageMap.put("path", path);
                 uploadImageMap.put("phoUrl", phoUrl);
                 return uploadImageMap;  
            }catch(Exception e){
                uploadImageMap.put("err", "上传文件失败！");   
                return uploadImageMap;   
            }
        }else{
            uploadImageMap.put("err", "上传文件失败！");
            return uploadImageMap;   
        }  
    }  

	
}
